const { BrowserWindow }  =  require("electron");
const electronLocalshortcut = require('electron-localshortcut');

var HID = require('node-hid');
// HID.setDriverType('libusb')
const hidDevices = [];

const sendLog = (msg)=>{
  const mainWin = BrowserWindow.getAllWindows()  //main
  mainWin.forEach(win=>{
    win.webContents.send('keyWatcher',msg)
  })
}

let inputs = []
const PID = [10203] //27db
//vid：5824 --->16c0

module.exports.shortWatch = function(win){
  HID.devices().forEach(deviceInfo => {
    const path = deviceInfo.path
    if(PID.includes(deviceInfo.productId)){
      console.log(JSON.stringify(deviceInfo))
      try{
        console.log(`try hid device : ${path}`)
        device = new HID.HID( path );
        device.on("data", function() {
          setCurrentPath(path)
        });
        device.on('error',function(err){
          console.log(err)
        })
        hidDevices.push(device)
      }catch(e){
        console.log('error:',e)
      } 
    }
  })

  win.on('close',function(){
    hidDevices.forEach(d=>{
      d.close()
    })
  })

  win.webContents.on('before-input-event', (event, input) => {
    // For example, only enable application menu keyboard shortcuts when
    // Ctrl/Cmd are down.
    win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta)

    // code value:https://developer.mozilla.org/zh-CN/docs/Web/API/KeyboardEvent/code#Code_values
    const v = `${input.key}`
    if(input.type === 'keyUp' && v.length && /^[a-zA-Z0-9]{0,1}$/ig.test(v)){
      console.log('v====>',v)
      inputs.push(v)
    }
  })
  electronLocalshortcut.register(win, 'Enter', () => {
    sendLog(`当前path：${setCurrentPath.path}====>${inputs.join('')}`)
    inputs = [];
  });
}

function setCurrentPath(path){
  setCurrentPath.path = path
}